// 环形图片
import { useEffect, useRef } from 'react'
import * as THREE from 'three'
import './App.css'
import { gsap } from 'gsap'
// 导入GLTFLoader用于加载GLB模型
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'

import { motion, useScroll, useSpring } from 'framer-motion';

// 添加轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

function App() {

  const containerRef = useRef(null)
  const scrollContainerRef = useRef(null) // 滚动容器的引用
  const scrollY = useRef(0);
  const { scrollYProgress } = useScroll({
    container: scrollContainerRef,
  });
  const scaleX = useSpring(scrollYProgress, { stiffness: 400, damping: 40 });
  useEffect(() => {
    // 让 scrollContainer 变成平滑滚动
    gsap.to(scrollContainerRef.current, {
      scrollTop: () => scrollY.current,
      ease: 'power2.out',
      duration: 0.4
    })
  }, [])
  useEffect(() => {
    // 场景
    const scene = new THREE.Scene()
    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      50,//相机的角度
      window.innerWidth / window.innerHeight,//相机的宽高比
      0.01,//相机的近截面
      100//相机的远截面
    )
    camera.position.z = 13
    camera.position.y = 2
    camera.position.x = 0
    camera.lookAt(0, 2, 0)

    // 创建渲染器时设置为全屏
    const renderer = new THREE.WebGLRenderer({
      antialias: true, // 抗锯齿
      alpha: true // 支持透明背景
    })
    renderer.setSize(window.innerWidth, window.innerHeight)
    renderer.setPixelRatio(window.devicePixelRatio) // 支持高DPI屏幕

    // 将渲染器添加到容器
    if (containerRef.current) {
      containerRef.current.appendChild(renderer.domElement)
    }



    // --------------------------------main-----------------------------------------------------------------------------------
    // 创建一个场景图
    const baseObrit = new THREE.Object3D()
    baseObrit.position.set(0, 0, 0)
    scene.add(baseObrit)

    // 创建模型场景图
    const modelObrit = new THREE.Object3D()
    modelObrit.position.set(0, 0, 0)
    scene.add(modelObrit)

    function addStar() {
      const geometry = new THREE.SphereGeometry(0.25, 24, 24);
      const material = new THREE.MeshPhongMaterial({ color: 0xfbc017 });

      const star = new THREE.Mesh(geometry, material);

      const [x, y, z] = Array(3)
        .fill()
        .map(() => THREE.MathUtils.randFloatSpread(100));

      star.position.set(x, y, z);
      baseObrit.add(star);
    }

    Array(200).fill().forEach(addStar);

    // GLB模型加载相关xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    const gltfLoader = new GLTFLoader();
    let loadedModel = null;
    gltfLoader.load(
      // 模型路径 - 使用你项目中的quit.glb文件
      '/glbExample/quit.glb',

      // 加载成功的回调函数
      (gltf) => {
        console.log('GLB模型加载成功:', gltf);

        // 获取模型场景
        loadedModel = gltf.scene;

        // 设置模型位置、旋转和缩放
        loadedModel.position.set(0, 0, 0); // 设置模型位置
        // loadedModel.scale.set(2, 2, 2); // 放大模型2倍
        // loadedModel.rotation.y = Math.PI; // 旋转180度

        // 遍历模型中的所有网格，设置材质属性
        loadedModel.traverse((child) => {
          if (child.isMesh) {
            // 启用阴影投射和接收
            child.castShadow = true;
            child.receiveShadow = true;

            // 如果材质存在，可以修改材质属性
            if (child.material) {
              // 确保材质能够接收光照
              child.material.needsUpdate = true;
            }
          }
        });

        // 检查是否有动画
        // if (gltf.animations && gltf.animations.length > 0) {
        //   console.log('发现动画:', gltf.animations.length, '个');

        //   // 创建动画混合器
        //   mixer = new THREE.AnimationMixer(loadedModel);

        //   // 播放所有动画
        //   gltf.animations.forEach((clip, index) => {
        //     console.log(`播放动画 ${index + 1}: ${clip.name}`);
        //     const action = mixer.clipAction(clip);
        //     action.play();
        //   });
        // }

        // 将模型添加到场景中
        modelObrit.add(loadedModel);
      },

      // 加载进度回调函数
      (progress) => {
        const percentComplete = (progress.loaded / progress.total) * 100;
        console.log(`GLB模型加载进度: ${percentComplete.toFixed(2)}%`);
      },

      // 加载错误回调函数
      (error) => {
        console.error('GLB模型加载失败:', error);
      }
    );


    // 图片相关xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    const loader = new THREE.TextureLoader();
    const imageCount = 12;
    const radius = 10;
    const group = new THREE.Group();

    // 设置统一的最大尺寸，保持图片比例
    const maxSize = 3; // 最大边长
    for (let i = 0; i < imageCount; i++) {
      const imgPath = `/images/${i + 1}.jpg`; // 自动拼接路径

      // 使用回调函数处理纹理加载完成后的逻辑
      loader.load(imgPath, (texture) => {
        // 水平翻转纹理
        texture.wrapS = THREE.RepeatWrapping;
        texture.repeat.x = -1;

        // 获取图片的原始尺寸
        const image = texture.image;
        const imageWidth = image.width;
        const imageHeight = image.height;

        // 计算图片的宽高比
        const aspectRatio = imageWidth / imageHeight;

        // 根据宽高比计算平面的实际尺寸，保持最大边长不超过maxSize
        let planeWidth, planeHeight;
        if (aspectRatio > 1) {
          // 宽图：宽度为maxSize，高度按比例缩放
          planeWidth = maxSize;
          planeHeight = maxSize / aspectRatio;
        } else {
          // 高图：高度为maxSize，宽度按比例缩放
          planeHeight = maxSize;
          planeWidth = maxSize * aspectRatio;
        }

        // 创建材质，设置透明度
        const material = new THREE.MeshBasicMaterial({
          map: texture,
          side: THREE.DoubleSide,
          transparent: true, // 启用透明度
          alphaTest: 0.1 // 设置alpha测试值，低于此值的像素将被丢弃
        });

        // 使用计算出的尺寸创建平面几何体
        const plane = new THREE.Mesh(new THREE.PlaneGeometry(planeWidth, planeHeight), material);

        // 极坐标计算位置
        const angle = (i / imageCount) * Math.PI * 2;
        plane.position.set(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);
        plane.lookAt(0, 0, 0);

        // 将平面添加到组中
        group.add(plane);
      },

      );
    }
    // 设置组的位置
    group.position.set(0, 2, 0);
    baseObrit.add(group)

    // scene.fog = new THREE.FogExp2(0x000000, 0.1)
    // 设置背景
    scene.background = new THREE.Color(0x000)

    // 添加地面xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    // 加载纹理
    const planeSize = 40;
    loader.load('./checker.png', (texture) => {
      texture.wrapS = THREE.RepeatWrapping;
      texture.wrapT = THREE.RepeatWrapping;
      texture.magFilter = THREE.NearestFilter;
      texture.colorSpace = THREE.SRGBColorSpace;
      const repeats = planeSize / 2;
      texture.repeat.set(repeats, repeats);
      const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
      const planeMat = new THREE.MeshPhongMaterial({
        map: texture,
        side: THREE.DoubleSide,
      });
      const mesh = new THREE.Mesh(planeGeo, planeMat);
      mesh.rotation.x = Math.PI * -.5;
      scene.add(mesh);
    });

    // 光源相关xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    // 添加点光源
    const color = 0xFFFFFF;
    const intensity = 150;
    const light = new THREE.PointLight(color, intensity);
    light.position.set(0, 10, 0);
    scene.add(light);
    // 添加环境光
    const ambientLight = new THREE.AmbientLight(0xffffff, 1);
    scene.add(ambientLight);

    // --------------------------------事件监听器-----------------------------------------------------------------------------------

    // 滚动事件处理函数
    const handleScroll = () => {
      if (scrollContainerRef.current) {
        scrollY.current = scrollContainerRef.current.scrollTop;
      }
    };

    // 窗口大小变化处理函数
    const handleResize = () => {
      // 更新相机宽高比
      camera.aspect = window.innerWidth / window.innerHeight
      camera.updateProjectionMatrix()

      // 更新渲染器尺寸
      renderer.setSize(window.innerWidth, window.innerHeight)
      renderer.setPixelRatio(window.devicePixelRatio)
    }

    // 确保DOM元素已经渲染
    const addEventListeners = () => {
      if (scrollContainerRef.current) {
        scrollContainerRef.current.addEventListener('scroll', handleScroll);
      }
    };

    // 延迟执行以确保DOM已渲染
    addEventListeners()
    window.addEventListener('resize', handleResize);

    // --------------------------------渲染循环-----------------------------------------------------------------------------------

    // 渲染函数
    function animate() {
      requestAnimationFrame(animate)

      // // 根据滚动位置计算旋转角度
      const rotationY = scrollY.current * 0.001;
      baseObrit.rotation.y = -rotationY;

      // 旋转
      modelObrit.rotation.y -= 0.005;


      // 渲染场景
      renderer.render(scene, camera)
    }

    // 启动渲染循环
    animate()

    // --------------------------------清理函数-----------------------------------------------------------------------------------

    // 清理函数
    return () => {
      // 移除事件监听器
      if (scrollContainerRef.current) {
        scrollContainerRef.current.removeEventListener('scroll', handleScroll);
      }
      window.removeEventListener('resize', handleResize);

      // 清理Three.js资源
      renderer.dispose();

      // 移除DOM元素
      if (containerRef.current && renderer.domElement) {
        containerRef.current.removeChild(renderer.domElement)
      }
    }
  }, [])

  return (
    // 隐藏滚动条
    <div
      ref={scrollContainerRef}
      className='container w-full h-[100vh] overflow-auto hide-scrollbar'
      style={{
        overflowY: 'auto',
        height: '100vh'
      }}
    >
      <div
        ref={containerRef}
        style={{
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          zIndex: -1,
          pointerEvents: 'none' // 防止阻挡页面交互
        }}
      />
      <motion.div
        style={{
          scaleX,
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          height: 4,
          background: '#ef4444',
          transformOrigin: '0% 0%',
          zIndex: 9999,
        }}
      />

      <div className="z-10 w-full sec">
        第一屏内容
      </div>
      <div className="z-10 w-full sec">
        第二屏内容
      </div>
      <div className="z-10 w-full sec">
        第三屏内容
      </div>
      <div className="z-10 w-full sec">
        第四屏内容
      </div>

    </div>
  )
}

export default App
